package cn.micai.base.lambda;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 * 描述：Java 8 – StringJoiner example
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/6/22 15:27
 */
public class StringJoinerExample {

    public static void main(String [] args) {

        // 1. StringJoiner
        StringJoiner sj = new StringJoiner(",");
        sj.add("aa");
        sj.add("bb");
        sj.add("cc");
        System.out.println(sj.toString());

        StringJoiner sj2 = new StringJoiner(",");
        sj2.add("ee");
        sj2.add("ff");
        sj2.add("gg");
        StringJoiner merge = sj.merge(sj2);
        System.out.println(merge.toString());

        StringJoiner stringJoiner = new StringJoiner("/", "prefix-", "-suffix");
        stringJoiner.add("2018");
        stringJoiner.add("06");
        stringJoiner.add("22");
        System.out.println(stringJoiner.toString());

        // 2. String.join
        String join = String.join("-", "2018", "06", "22");
        System.out.println(join);

        List<String> list = Arrays.asList("java","python","nodejs","ruby");
        String join1 = String.join(", ", list);
        System.out.println(join1);


        // 3. Collectors.joining

        // java | python | nodejs | ruby
        String collect = list.stream().map(x -> x).collect(Collectors.joining(" | "));
        System.out.println(collect);

        List<Game> games = Arrays.asList(
                new Game("Dragon Blaze", 5),
                new Game("Angry Bird", 5),
                new Game("Candy Crush", 5)
        );

        // {Dragon Blaze, Angry Bird, Candy Crush}
        String collect1 = games.stream().map(x -> x.getName()).collect(Collectors.joining(", ", "{", "}"));
        System.out.println(collect1);


    }

    static class Game {
        String name;
        int ranking;

        public Game(String name, int ranking) {
            this.name = name;
            this.ranking = ranking;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getRanking() {
            return ranking;
        }

        public void setRanking(int ranking) {
            this.ranking = ranking;
        }

        @Override
        public String toString() {
            return "Game{" +
                    "name='" + name + '\'' +
                    ", ranking=" + ranking +
                    '}';
        }
    }
}
